package io.itit.ecp.admin.provide.action.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.itit.ecp.admin.common.utils.EcpAdminUtils;
import io.itit.ecp.admin.provide.action.req.CarbonSinkFactorQueryReq;
import io.itit.ecp.admin.provide.action.req.CarbonSinkFactorReq;
import io.itit.ecp.admin.provide.action.resp.CarbonSinkFactorResp;
import io.itit.ecp.admin.provide.filter.ICarbonSinkFactorFilter;
import io.itit.ecp.admin.provide.helper.CarbonSinkFactorHelper;
import io.itit.ecp.admin.provide.renderer.CarbonSinkFactorRenderer;
import io.itit.ecp.admin.server.entity.CarbonSinkFactorEntity;
import io.itit.ecp.admin.server.service.ICarbonSinkFactorService;
import io.itit.grass.common.exception.GrassException;
import io.itit.grass.common.provide.action.req.BaseBatchIdReq;
import io.itit.grass.common.provide.action.req.BaseIdReq;
import io.itit.grass.common.provide.action.resp.ResultResp;
import io.itit.grass.common.provide.action.validation.*;
import io.itit.grass.common.server.utils.ConvertUtils;
import io.itit.grass.estelle.starter.core.ExcelXSSFUtil;
import io.itit.grass.estelle.starter.parse.ExcelParseManage;
import io.itit.grass.estelle.starter.util.JsonUtil;
import io.itit.grass.web.wall.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：碳汇因子控制类
 * @Date：Create by 2023-11-23 16:12:43
 */
@Api(tags = "碳汇因子")
@RestController
@RequestMapping("/ecp-admin/carbonSinkFactor")
public class CarbonSinkFactorController {

    @Resource
    private ICarbonSinkFactorService carbonSinkFactorService;

    @ApiOperation("分页查询")
    @PostMapping("queryPage")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:search")
    public ResultResp<IPage<CarbonSinkFactorResp>> queryPage(@RequestBody @Validated(IQueryPage.class) CarbonSinkFactorQueryReq req) {
        Page<CarbonSinkFactorEntity> page = carbonSinkFactorService.page(PageUtils.getPage(req, CarbonSinkFactorEntity.class), buildQW(req));
        return ResultResp.success(ConvertUtils.convert(page, CarbonSinkFactorResp.class));
    }

    @ApiOperation("列表查询")
    @PostMapping("queryList")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:search")
    public ResultResp<List<CarbonSinkFactorResp>> queryList(@RequestBody CarbonSinkFactorQueryReq req) {
        List<CarbonSinkFactorEntity> list = carbonSinkFactorService.list(buildQW(req));
        return ResultResp.success(ConvertUtils.convert(list, CarbonSinkFactorResp.class));
    }

    @ApiOperation("详情")
    @PostMapping("detail")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:search")
    public ResultResp<CarbonSinkFactorResp> detail(@RequestBody @Validated(IRequired.class) BaseIdReq req) {
        return ResultResp.success(ConvertUtils.copy(carbonSinkFactorService.getById(req.getId()), CarbonSinkFactorResp.class));
    }

    /**
     * 组装查询条件
     *
     * @param req
     * @return
     */
    private static LambdaQueryWrapper<CarbonSinkFactorEntity> buildQW(CarbonSinkFactorQueryReq req) {
        LocalDateTime dateStart = null;
        LocalDateTime dateEnd = null;
        if (StringUtils.isNotEmpty(req.getSolidifyDate())) {
            YearMonth yearMonth = YearMonth.parse(req.getSolidifyDate(), DateTimeFormatter.ofPattern("yyyy-MM"));
            dateStart = yearMonth.atDay(1).atTime(LocalTime.MIN);
            dateEnd = LocalDate.of(yearMonth.getYear(), yearMonth.getMonth(), yearMonth.lengthOfMonth()).atTime(LocalTime.MAX);
        }
        return Wrappers.<CarbonSinkFactorEntity>lambdaQuery()
                .ge(StringUtils.isNotEmpty(req.getSolidifyDateStart()), CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDateStart())
                .le(StringUtils.isNotEmpty(req.getSolidifyDateEnd()), CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDateEnd())
                .eq(StringUtils.isNotEmpty(req.getType()), CarbonSinkFactorEntity::getType, req.getType())
                .eq(req.getFactor() != null, CarbonSinkFactorEntity::getFactor, req.getFactor())
                .eq(StringUtils.isNotEmpty(req.getUnit()), CarbonSinkFactorEntity::getUnit, req.getUnit())
                .eq(StringUtils.isNotEmpty(req.getRemark()), CarbonSinkFactorEntity::getRemark, req.getRemark())
                .eq(StringUtils.isNotEmpty(req.getDeptId()), CarbonSinkFactorEntity::getDeptId, req.getDeptId())
                .in(CollectionUtils.isNotEmpty(req.getIds()), CarbonSinkFactorEntity::getId, req.getIds())
                .ge(Objects.nonNull(dateStart), CarbonSinkFactorEntity::getSolidifyDate, dateStart)
                .lt(Objects.nonNull(dateEnd), CarbonSinkFactorEntity::getSolidifyDate, dateEnd)
                .orderByDesc(CarbonSinkFactorEntity::getSolidifyDate)
                .orderByDesc(CarbonSinkFactorEntity::getCreateTm);
    }

    @ApiOperation("新增")
    @PostMapping("add")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:add")
    public ResultResp<Boolean> add(@RequestBody @Validated({IAdd.class}) CarbonSinkFactorReq req) {
        Long count = carbonSinkFactorService.lambdaQuery()
                .eq(CarbonSinkFactorEntity::getType, req.getType())
                .eq(CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDate())
                .count();
        GrassException.throwEx(count > 0, "数据已存在，不能重复新增。");
        CarbonSinkFactorHelper.i().setCache(req.getType(), req.getSolidifyDate(), req.getFactor());
        return ResultResp.success(carbonSinkFactorService.save(ConvertUtils.convertIgnoreId(req, CarbonSinkFactorEntity.class)));
    }

    @ApiOperation("批量新增")
    @PostMapping("batchAdd")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:add")
    public ResultResp<Boolean> batchAdd(@RequestBody @Validated({IBatch.class}) CarbonSinkFactorReq req) {
        Long count = carbonSinkFactorService.lambdaQuery()
                .eq(CarbonSinkFactorEntity::getType, req.getType())
                .ge(CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDateStart())
                .le(CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDateEnd())
                .count();
        GrassException.throwEx(count > 0, "该时段已存在碳汇因子，不能重复新增!");

        int compare = req.getSolidifyDateStart().compareTo(req.getSolidifyDateEnd());
        GrassException.throwEx(compare > 0, "结束时间不能大于开始时间！");

        // 组装批量新增数据
        List<CarbonSinkFactorEntity> entityList = IntStream.range(0, EcpAdminUtils.between(req.getSolidifyDateStart(), req.getSolidifyDateEnd(), ChronoUnit.MONTHS).intValue() + 1)
                .mapToObj(t -> {
                    Date newDate = DateUtils.addMonths(req.getSolidifyDateStart(), t);
                    CarbonSinkFactorEntity entity = new CarbonSinkFactorEntity();
                    entity.setSolidifyDate(newDate);
                    entity.setType(req.getType());
                    entity.setFactor(req.getFactor());
                    entity.setRemark(req.getRemark());
                    return entity;
                })
                .collect(Collectors.toList());

        return ResultResp.success(carbonSinkFactorService.saveBatch(entityList, 1000));
    }

    @ApiOperation("编辑")
    @PostMapping("update")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:update")
    public ResultResp<Boolean> update(@RequestBody @Validated({IUpdate.class}) CarbonSinkFactorReq req) {
        boolean bool = carbonSinkFactorService.updateCarbonSinkFactor(ConvertUtils.copy(req, CarbonSinkFactorEntity.class));
        CarbonSinkFactorHelper.i().setCache(req.getType(), req.getSolidifyDate(), req.getFactor());
        return ResultResp.success(bool);
    }

    @ApiOperation("批量编辑")
    @PostMapping("batchUpdate")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:update")
    public ResultResp<Boolean> batchUpdate(@RequestBody @Validated({IBatch.class}) CarbonSinkFactorReq req) {
        Long count = carbonSinkFactorService.lambdaQuery()
                .eq(CarbonSinkFactorEntity::getType, req.getType())
                .ge(CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDateStart())
                .le(CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDateEnd())
                .count();
        GrassException.throwEx(count == 0, "该时段无碳汇因子数据，无需更新（如有需要可批量新增）!");

        return ResultResp.success(carbonSinkFactorService.lambdaUpdate()
                .set(CarbonSinkFactorEntity::getFactor, req.getFactor())
                .set(CarbonSinkFactorEntity::getRemark, req.getRemark())
                .eq(CarbonSinkFactorEntity::getType, req.getType())
                .ge(CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDateStart())
                .le(CarbonSinkFactorEntity::getSolidifyDate, req.getSolidifyDateEnd())
                .update());
    }

    @ApiOperation("删除(根据Id删)")
    @PostMapping("deleteById")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:deleteById")
    public ResultResp<Boolean> deleteById(@RequestBody @Validated({IRequired.class}) BaseIdReq req) {
        return ResultResp.success(carbonSinkFactorService.removeById(req.getId()));
    }

    @ApiOperation("批量删除")
    @PostMapping("batchDelete")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:batchDelete")
    public ResultResp<Boolean> batchDelete(@RequestBody @Validated({IRequired.class}) BaseBatchIdReq req) {
        return ResultResp.success(carbonSinkFactorService.removeBatchByIds(req.getIds(), 1000));
    }

    @ApiOperation("导入")
    @PostMapping("upload")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:upload")
    public ResultResp<Integer> upload(@RequestParam("file") MultipartFile file, Boolean ignoreError) {
        return ResultResp.success(ExcelParseManage.i().process(CarbonSinkFactorRenderer.ENTITY_NAME, file, ignoreError));
    }

    @ApiOperation("导出")
    @PostMapping("export")
    @RequiresPermissions("ecp-admin:carbonSinkFactor:export")
    public void export(@RequestBody @Validated(IExport.class) CarbonSinkFactorQueryReq req, HttpServletResponse response) {
        ExcelXSSFUtil.export("CarbonSinkFactorExport", JsonUtil.toJson(carbonSinkFactorService.list(buildQW(req)), new ICarbonSinkFactorFilter.CarbonSinkFactorExportFilter()), response);
    }
}
